/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dragoncon.dcsched.ui;

import com.dragoncon.dcsched.R;
import com.dragoncon.dcsched.provider.ScheduleContract;
import com.dragoncon.dcsched.util.ActivityHelper;
import com.dragoncon.dcsched.util.AnalyticsUtils;
import com.dragoncon.dcsched.util.BitmapUtils;
import com.dragoncon.dcsched.util.FractionalTouchDelegate;
import com.dragoncon.dcsched.util.NotifyingAsyncQueryHandler;
import com.dragoncon.dcsched.util.ParserUtils;
import com.dragoncon.dcsched.util.UIUtils;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

/**
 * A fragment that shows detail information for a sandbox company, including company name,
 * description, product description, logo, etc.
 */
public class SpeakerDetailFragment extends Fragment implements
        NotifyingAsyncQueryHandler.AsyncQueryListener,
        CompoundButton.OnCheckedChangeListener {
    private static final String TAG = "SpeakerDetailFragment";

    /**
     * Since sessions can belong tracks, the parent activity can send this extra specifying a
     * track URI that should be used for coloring the title-bar.
     */
    public static final String EXTRA_TRACK = "com.dragoncon.dcsched.extra.TRACK";

    private static final String TAG_SUMMARY = "summary";
    private static final String TAG_NOTES = "notes";
    private static final String TAG_LINKS = "links";

    private String mSpeakerId;
    private Uri mSpeakerUri;

    private ViewGroup mRootView;
    private TabHost mTabHost;
    private TextView mName;
    private CompoundButton mStarred;

    private ImageView mLogo;
    private TextView mAbstract;
    
    private String mNameString;

    private NotifyingAsyncQueryHandler mHandler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments());
        mSpeakerUri = intent.getData();
        if (mSpeakerUri== null) {
            return;
        }

        mSpeakerId = ScheduleContract.Speakers.getSpeakerId(mSpeakerUri);

        setHasOptionsMenu(true);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (mSpeakerUri == null) {
            return;
        }

        // Start background queries to load session and track details
        final Uri sessionsUri = ScheduleContract.Speakers.buildSessionsDirUri(mSpeakerId);

        // Start background query to load speaker details
        mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this);
        mHandler.startQuery(SpeakersQuery._TOKEN, mSpeakerUri, SpeakersQuery.PROJECTION);
        mHandler.startQuery(SessionsQuery._TOKEN, sessionsUri, SessionsQuery.PROJECTION);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_speaker_detail, null);
        mTabHost = (TabHost) mRootView.findViewById(android.R.id.tabhost);
        mTabHost.setup();

        mName = (TextView) mRootView.findViewById(R.id.speaker_name);
        mStarred = (CompoundButton) mRootView.findViewById(R.id.speaker_star_button);

        mStarred.setFocusable(true);
        mStarred.setClickable(true);

        // Larger target triggers star toggle
        final View starParent = mRootView.findViewById(R.id.header_speaker);
        FractionalTouchDelegate.setupDelegate(starParent, mStarred, new RectF(0.6f, 0f, 1f, 0.8f));

        mLogo = (ImageView) mRootView.findViewById(R.id.speaker_logo);
        mAbstract = (TextView) mRootView.findViewById(R.id.speaker_abstract);

        setupSummaryTab();
        setupNotesTab();
        setupLinksTab();

        return mRootView;
    }

    /**
     * Build and add "summary" tab.
     */
    private void setupSummaryTab() {
        // Summary content comes from existing layout
        mTabHost.addTab(mTabHost.newTabSpec(TAG_SUMMARY)
                .setIndicator(buildIndicator(R.string.speaker_summary))
                .setContent(R.id.tab_speaker_summary));
    }

    /**
     * Build and add "notes" tab.
     */
    private void setupNotesTab() {
        // Make powered-by clickable
        ((TextView) mRootView.findViewById(R.id.notes_powered_by)).setMovementMethod(
                LinkMovementMethod.getInstance());

        // Setup tab
        mTabHost.addTab(mTabHost.newTabSpec(TAG_NOTES)
                .setIndicator(buildIndicator(R.string.speaker_notes))
                .setContent(R.id.tab_speaker_notes));
    }

    /**
     * Build and add "summary" tab.
     */
    private void setupLinksTab() {
        // Summary content comes from existing layout
        mTabHost.addTab(mTabHost.newTabSpec(TAG_LINKS)
                .setIndicator(buildIndicator(R.string.speaker_links))
                .setContent(R.id.tab_speaker_links));
    }

    private void updateLinksTab(Cursor cursor) {
        ViewGroup container = (ViewGroup) mRootView.findViewById(R.id.links_container);

        // Remove all views but the 'empty' view
        int childCount = container.getChildCount();
        if (childCount > 1) {
            container.removeViews(1, childCount - 1);
        }

	// TODO
        container.findViewById(R.id.empty_links).setVisibility(View.VISIBLE);
    }

    /**
     * Build a {@link android.view.View} to be used as a tab indicator, setting the requested string resource as
     * its label.
     *
     * @return View
     */
    private View buildIndicator(int textRes) {
        final TextView indicator = (TextView) getActivity().getLayoutInflater()
                .inflate(R.layout.tab_indicator,
                        (ViewGroup) mRootView.findViewById(android.R.id.tabs), false);
        indicator.setText(textRes);
        return indicator;
    }

    /**
     * {@inheritDoc}
     */
    public void onQueryComplete(int token, Object cookie, Cursor cursor) {
        if (getActivity() == null) {
            return;
        }

        if (token == SpeakersQuery._TOKEN) {
            onSpeakerQueryComplete(cursor);
	} else if(token == SessionsQuery._TOKEN) {
	    onSessionsQueryComplete(cursor);
        } else {
            cursor.close();
	}
    }

    private void onSessionsQueryComplete(Cursor cursor) {
        try {
            // TODO: remove any existing sessions from layout, since this cursor
            // might be from a data change notification.
            final ViewGroup sessionsGroup = (ViewGroup)
                    mRootView.findViewById(R.id.speaker_sessions_block);
            final LayoutInflater inflater = getActivity().getLayoutInflater();

            boolean hasSessions = false;

            while (cursor.moveToNext()) {
                final String sessionTitle = cursor.getString(SessionsQuery.TITLE);
                if (TextUtils.isEmpty(sessionTitle)) {
                    continue;
                }

		// Format time block this session occupies
		final long blockStart = cursor.getLong(SessionsQuery.BLOCK_START);
		final long blockEnd = cursor.getLong(SessionsQuery.BLOCK_END);
		final int starred = cursor.getInt(SessionsQuery.STARRED);
		final String roomName = cursor.getString(SessionsQuery.ROOM_NAME);
		final String roomBldg = cursor.getString(SessionsQuery.ROOM_BUILDING);
		final String roomFloor = cursor.getString(SessionsQuery.ROOM_FLOOR);
		final String sessionAbstract = cursor.getString(SessionsQuery.ABSTRACT);

		final String roomTitle = String.format("%s [%s %s]", roomName, roomBldg, roomFloor);
		final String subtitle = UIUtils.formatSessionSubtitle(blockStart,
								      blockEnd, roomTitle, getActivity());

                final View sessionView = inflater
                        .inflate(R.layout.list_item_session, sessionsGroup, false);
                final TextView sessionTitleView = (TextView) sessionView
                        .findViewById(R.id.session_title);
                final TextView sessionSubtitleView = (TextView) sessionView
                        .findViewById(R.id.session_subtitle);
		final ImageView sessionStarredView = (ImageView) sessionView
		        .findViewById(R.id.session_star_button);

                //final TextView sessionAbstractView = (TextView) sessionView
		//.findViewById(R.id.session_abstract);

                sessionTitleView.setText(sessionTitle);
                sessionSubtitleView.setText(subtitle);
		sessionStarredView.setVisibility(starred != 0 ? View.VISIBLE : View.GONE);
                //UIUtils.setTextMaybeHtml(sessionAbstractView, sessionAbstract);

                sessionsGroup.addView(sessionView);
                hasSessions = true;
	    }

            sessionsGroup.setVisibility(hasSessions ? View.VISIBLE : View.GONE);
        } finally {
            if (null != cursor) {
                cursor.close();
            }
        }
    }

    private void onSpeakerQueryComplete(Cursor cursor) {
        try {
            if (!cursor.moveToFirst()) {
                return;
            }

            mNameString = cursor.getString(SpeakersQuery.NAME);
            mName.setText(mNameString);

            // Unregister around setting checked state to avoid triggering
            // listener since change isn't user generated.
            mStarred.setOnCheckedChangeListener(null);
            mStarred.setChecked(cursor.getInt(SpeakersQuery.STARRED) != 0);
            mStarred.setOnCheckedChangeListener(this);

            // Start background fetch to load speaker logo
            final String logoUrl = cursor.getString(SpeakersQuery.IMAGE_URL);

            if (!TextUtils.isEmpty(logoUrl)) {
                BitmapUtils.fetchImage(getActivity(), logoUrl, null, null,
                        new BitmapUtils.OnFetchCompleteListener() {
                            public void onFetchComplete(Object cookie, Bitmap result) {
                                if (result == null) {
                                    mLogo.setVisibility(View.GONE);
                                } else {
                                    mLogo.setVisibility(View.VISIBLE);
                                    mLogo.setImageBitmap(result);
                                }
                            }
                        });
            }

            mAbstract.setText(cursor.getString(SpeakersQuery.ABSTRACT));

            // Assign track details when found
            // TODO: handle speakers not attached to track

            AnalyticsUtils.getInstance(getActivity()).trackPageView(
                    "/Speakers/" + mNameString);

        } finally {
            cursor.close();
        }
    }

    /**
     * Handle toggling of starred checkbox.
     */
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        final ContentValues values = new ContentValues();
        values.put(ScheduleContract.Speakers.SPEAKER_STARRED, isChecked ? 1 : 0);
        mHandler.startUpdate(mSpeakerUri, values);

        AnalyticsUtils.getInstance(getActivity()).trackEvent(
                "Speaker", isChecked ? "Starred" : "Unstarred", mNameString, 0);
    }

    /**
     * {@link com.dragoncon.dcsched.provider.ScheduleContract.Speakers} query parameters.
     */
    private interface SpeakersQuery {
        int _TOKEN = 0x1;

        String[] PROJECTION = {
                ScheduleContract.Speakers.SPEAKER_NAME,
                ScheduleContract.Speakers.SPEAKER_IMAGE_URL,
                ScheduleContract.Speakers.SPEAKER_COMPANY,
                ScheduleContract.Speakers.SPEAKER_ABSTRACT,
                ScheduleContract.Speakers.SPEAKER_URL,
		ScheduleContract.Speakers.SPEAKER_STARRED,
        };

        int NAME = 0;
        int IMAGE_URL = 1;
        int COMPANY = 2;
        int ABSTRACT = 3;
        int URL = 4;
	int STARRED = 5;
    }

    private interface SessionsQuery {
        int _TOKEN = 0x2;
	
        String[] PROJECTION = {
                ScheduleContract.Blocks.BLOCK_START,
                ScheduleContract.Blocks.BLOCK_END,
                ScheduleContract.Sessions.SESSION_LEVEL,
                ScheduleContract.Sessions.SESSION_TITLE,
                ScheduleContract.Sessions.SESSION_ABSTRACT,
                ScheduleContract.Sessions.SESSION_REQUIREMENTS,
                ScheduleContract.Sessions.SESSION_STARRED,
                ScheduleContract.Sessions.SESSION_HASHTAG,
                ScheduleContract.Sessions.SESSION_SLUG,
                ScheduleContract.Sessions.SESSION_URL,
                ScheduleContract.Sessions.SESSION_MODERATOR_URL,
                ScheduleContract.Sessions.SESSION_YOUTUBE_URL,
                ScheduleContract.Sessions.SESSION_PDF_URL,
                ScheduleContract.Sessions.SESSION_FEEDBACK_URL,
                ScheduleContract.Sessions.SESSION_NOTES_URL,
                ScheduleContract.Sessions.ROOM_ID,
                ScheduleContract.Rooms.ROOM_NAME, 
                ScheduleContract.Rooms.ROOM_BUILDING,
                ScheduleContract.Rooms.ROOM_FLOOR,
	};

        int BLOCK_START = 0;
        int BLOCK_END = 1;
        int LEVEL = 2;
        int TITLE = 3;
        int ABSTRACT = 4;
        int REQUIREMENTS = 5;
        int STARRED = 6;
        int HASHTAG = 7;
        int SLUG = 8;
        int URL = 9;
        int MODERATOR_URL = 10;
        int YOUTUBE_URL = 11;
        int PDF_URL = 12;
        int FEEDBACK_URL = 13;
        int NOTES_URL = 14;
        int ROOM_ID = 15;
        int ROOM_NAME = 16;
        int ROOM_BUILDING = 17;
        int ROOM_FLOOR = 18;
    }
}
